package com.geeker.module.sys.user.sevice;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.geeker.common.exception.BusinessException;
import com.geeker.module.sys.user.domain.SysUser;
import com.geeker.module.sys.user.mapper.SysUserMapper;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SysUserService extends ServiceImpl<SysUserMapper, SysUser> {

    public void add(SysUser user) {
        List<SysUser> userNameList = this.list(QueryWrapper.create().eq(SysUser::getUserName, user.getUserName()));
        if (CollectionUtil.isNotEmpty(userNameList)) {
            throw new BusinessException("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        }
        if (StringUtils.isNotEmpty(user.getPassword())) {
            List<SysUser> phoneList = this.list(QueryWrapper.create().eq(SysUser::getPhone, user.getPhone()));
            if(CollectionUtil.isNotEmpty(phoneList))
                throw new BusinessException("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        }
        user.setPassword(DigestUtil.bcrypt(user.getPassword()));
        this.save(user);
    }
}
